package com.zhyonk.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.zhyonk.config.propreties.BaiduProperties;
import com.zhyonk.domain.FaceInfo;
import com.zhyonk.domain.StarUser;
import com.zhyonk.mapper.FaceInfoMapper;
import com.zhyonk.mapper.StarUserMapper;
import com.zhyonk.service.AsyncService;
import com.zhyonk.util.JsoupParserUtil;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service("asyncService")
public class AsyncServiceImpl implements AsyncService {

    @Autowired
    private StarUserMapper starUserMapper;

    @Autowired
    private FaceInfoMapper faceInfoMapper;

    @Autowired
    private BaiduProperties baiduProperties;


    @Override
    @Async
    public void execSetUserOption(StarUser user) {
        //获取到详细信息的链接
        String infoLink = user.getInfoLink();
        try {
            Document document = Jsoup.connect(infoLink).get();

            Element element = JsoupParserUtil.getSingleElementBySelectStr(document, "#headline .info");
            if (Objects.nonNull(element)){
                Elements elements = element.getElementsByTag("li");
                for (Element ele: elements) {
                    String text = ele.text();
//                    if (text.startsWith("星座: ")){
//                        user.setConstellation(text.replace("星座: ",""));
//                        continue;
//                    }
//                    if (text.startsWith("出生地: ")){
//                        user.setBirthPlace(text.replace("出生地: ",""));
//                        continue;
//                    }
//                    if (text.startsWith("出生日期: ")){
//                        String brithDateStr = text.replace("出生日期: ", "");
//                        DateTime parse = DateUtil.parse(brithDateStr);
//                        user.setBirthDate(parse);
//                        continue;
//                    }
//
//                    if (text.startsWith("职业: ")){
//                        user.setJob(text.replace("职业: ",""));
//                        continue;
//                    }
//                    if (text.startsWith("外文名: ")){
//                        user.setEnglishName(text.replace("外文名: ",""));
//                    }
                    if (text.startsWith("性别: ")){
                        String sex = text.replace("性别: ", "");
                        if ("男".equals(sex)){
                            user.setSex(1);
                        }else if ("女".equals(sex)){
                            user.setSex(0);
                        }else {
                            user.setSex(-1);
                        }
                    }
                }
                starUserMapper.updateById(user);
                System.out.println("完毕： "+user.getId() + ":" + user.getName() + "填充完毕");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    @Async
    public void execPushInfoToBaidu(StarUser user) {
        HashMap<String, String> option = new HashMap<>();
        HashMap<String, String> userInfo = new HashMap<>();
        userInfo.put("name",user.getName());
        userInfo.put("sex",user.getSex()+"");
        userInfo.put("constellation",user.getConstellation());
        userInfo.put("birthPlace",user.getBirthPlace());
        userInfo.put("birthDate",DateUtil.format(user.getBirthDate(), DatePattern.NORM_DATE_FORMAT));
        userInfo.put("job",user.getJob());
        userInfo.put("englishName",user.getEnglishName() == null?"未知":user.getEnglishName());
        option.put("user_info",com.alibaba.fastjson.JSONObject.toJSONString(userInfo));
        JSONObject jsonObject = baiduProperties.getAipFaceClient().addUser(user.getImgUrl(), "URL", "star", user.getId() + "", userInfo);
        FaceInfo faceInfo = null;
        try{

            Map<String, Object> toMap = jsonObject.toMap();
            JSONObject temp = new JSONObject(toMap);

            faceInfo = genFaceInfo(temp);
            user.setFaceToken(jsonObject.getJSONObject("result").getString("face_token"));
            starUserMapper.updateById(user);
            faceInfoMapper.insert(faceInfo);
            System.out.println("完毕： "+user.getId() + ":" + user.getName() + "上传完毕");
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("****错误****" + user.getName() + ": " + "更新推送失败!");
        }


    }

    private FaceInfo genFaceInfo(JSONObject jsonObject) throws Exception {
        if (jsonObject.getInt("error_code") !=0){
            //说明，报错了
            throw new Exception("error_code:" + jsonObject.getInt("error_code") + "\n" + "error_msg: " + jsonObject.getString("error_msg"));
        }
        jsonObject = jsonObject.getJSONObject("result");
        String faceToken = jsonObject.getString("face_token");
        jsonObject = jsonObject.getJSONObject("location");
        double left = jsonObject.getDouble("left");
        double top = jsonObject.getDouble("top");
        double width = jsonObject.getDouble("width");
        double height = jsonObject.getDouble("height");
        double rotation = jsonObject.getDouble("rotation");

        FaceInfo faceInfo = new FaceInfo();
        faceInfo.setFaceToken(faceToken);
        faceInfo.setHeight(height);
        faceInfo.setLeftl(left);
        faceInfo.setLocation(com.alibaba.fastjson.JSONObject.toJSONString(jsonObject.toMap()));
        faceInfo.setRotation(rotation);
        faceInfo.setTop(top);
        faceInfo.setWidth(width);
        return faceInfo;
    }

    public static void execSetUserOption1(StarUser user) {
        //获取到详细信息的链接
        String infoLink = user.getInfoLink();
        try {
            Document document = Jsoup.connect(infoLink).get();

            Element element = JsoupParserUtil.getSingleElementBySelectStr(document, "#headline .info");
            if (Objects.nonNull(element)){
                Elements elements = element.getElementsByTag("li");
                for (Element ele: elements) {
                    String text = ele.text();
                    if (text.startsWith("性别: ")){
                        String sex = text.replace("性别: ", "");
                        if ("男".equals(sex)){
                            user.setSex(1);
                        }else if ("女".equals(sex)){
                            user.setSex(0);
                        }else {
                            user.setSex(-1);
                        }
                    }
                }
//                userMapper.updateById(user);
                System.out.println("完毕： "+user.getId() + ":" + user.getName() + "填充完毕");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        StarUser user = new StarUser();
        user.setInfoLink("http://www.xrso.com/mingxing/143449/");
        AsyncServiceImpl.execSetUserOption1(user);

    }
}
